import { PrismaClient } from '@prisma/client';
import { randomUUID } from 'crypto';

enum UserRoleType {
  NORMAL = 'NORMAL', /// 普通用户
  VIP = 'VIP', /// VIP用户
}

const prisma = new PrismaClient();

async function main() {
  // 按顺序生成角色
  await prisma.userRole.upsert({
    where: { role: UserRoleType.NORMAL },
    update: { role: UserRoleType.NORMAL },
    create: { role: UserRoleType.NORMAL },
  });
  await prisma.userRole.upsert({
    where: { role: UserRoleType.VIP },
    update: { role: UserRoleType.VIP },
    create: { role: UserRoleType.VIP },
  });

  // 生成卡密
  const vipRole = await prisma.userRole.findUnique({ where: { role: UserRoleType.VIP } });
  if (!vipRole) throw new Error('VIP角色不存在');

  // 月卡/季卡/年卡 各生成 10000 个
  const existingCount = await prisma.cardKey.count();
  const targetTotal = 10000 * 3;

  if (existingCount < targetTotal) {
    // 生成月卡
    const monthKeys = Array.from({ length: 10000 }, () => ({
      key: randomUUID(),
      usedRoleId: vipRole.id,
      duration: 30,
    }));
    // 生成季卡
    const quarterKeys = Array.from({ length: 10000 }, () => ({
      key: randomUUID(),
      usedRoleId: vipRole.id,
      duration: 90,
    }));
    // 生成年卡
    const yearKeys = Array.from({ length: 10000 }, () => ({
      key: randomUUID(),
      usedRoleId: vipRole.id,
      duration: 365,
    }));

    await prisma.cardKey.createMany({
      data: [...monthKeys, ...quarterKeys, ...yearKeys, { key: 'admin12345678910', usedRoleId: vipRole.id, duration: 3650 }],
    });
  }
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(() => {
    prisma.$disconnect();
    console.log('================================================ Seed Done ================================================');
  });
